      1  import java.util.concurrent.locks.Lock;

      2  import java.util.concurrent.locks.ReentrantLock;

      3

      4  /**

      5     A bank account has a balance that can be changed by

      6     deposits and withdrawals.

      7  */

      8  public class BankAccount

      9  {

     10     private double balance;

     11     private Lock balanceChangeLock;

     12

     13     /**

     14        Constructs a bank account with a zero balance.

     15     */

     16     public BankAccount()

     17     {

     18        balance = 0;

     19        balanceChangeLock = new ReentrantLock();

     20     }

     21

     22     /**

     23        Constructs a bank account with a given balance.

     24        @param initialBalance the initial balance

     25     */

     26     public BankAccount(double initialBalance)

     27     {

     28        balance = initialBalance;

     29     }

     30

     31     /**

     32        Deposits money into the bank account.

     33        @param amount the amount to deposit

     34     */

     35     public void deposit(double amount)

     36     {

     37        balanceChangeLock.lock();

     38        try

     39        {

     40           double newBalance = balance + amount;

     41           balance = newBalance;

     42        }

     43        finally

     44        {

     45           balanceChangeLock.unlock();

     46        }

     47     }

     48

     49     /**

     50        Withdraws money from the bank account.

     51        @param amount the amount to withdraw

     52     */

     53     public void withdraw(double amount)

     54     {

     55        balanceChangeLock.lock();

     56        try

     57        {

     58           double newBalance = balance - amount;

     59           balance = newBalance;

     60        }

     61        finally

     62        {

     63           balanceChangeLock.unlock();

     64        }

     65     }

     66

     67     /**

     68        Gets the current balance of the bank account.

     69        @return the current balance

     70     */

     71     public double getBalance()

     72     {

     73        return balance;

     74     }

     75  }

     76